import { Config, Log_Prefix } from "#yenai.components"
import moment from "moment"
import { common } from "../../model/index.js"

const redisKeyPre = "yenai:notice:message"
const redisKeyPreGroup = redisKeyPre + "Group:"
const redisKeyPrePrivate = redisKeyPre + "Private:"
Bot.on?.("message", async (e) => {
  const bot = e.bot ?? Bot
  // 判断是否存在消息
  if (!e?.message?.length) return false
  // 判断是否为机器人消息
  if (e.user_id == bot.uin) return false
  // 判断是否主人消息
  if (Config.masterQQ.includes(e.user_id)) return false
  const cfg = Config.getNotice(e.self_id, e.group_id)
  const deltime = cfg.msgSaveDeltime
  // 判断群聊还是私聊
  if (e.message_type == "group" && cfg.groupRecall) {
    redis.set(
      redisKeyPreGroup + e.message_id,
      JSON.stringify({ message: e.message, group_id: e.group_id, user_id: e.user_id }),
      { EX: deltime }
    )
  } else if (e.message_type == "private" && cfg.PrivateRecall) {
    redis.set(
      redisKeyPrePrivate + e.message_id,
      JSON.stringify({ message: e.message, user_id: e.user_id }),
      { EX: deltime }
    )
  }
})

Bot.on?.("notice.group.recall", async (e) => {
  const bot = e.bot ?? Bot
  // 开启或关闭
  if (!Config.getNotice(e.self_id, e.group_id).groupRecall) return false
  // 是否为机器人撤回
  if (e.user_id == bot.uin || e.operator_id == bot.uin) return false
  // 是否为主人撤回
  if (Config.masterQQ.includes(e.user_id)) return false
  // 读取
  const rawMsg = JSON.parse(await redis.get(redisKeyPreGroup + e.message_id))
  // 无数据 return出去
  if (!rawMsg) return false
  const SpecialMsg = getSpecialMsgType(rawMsg)
  let special = ""
  let forwardMsg = null
  let msg = null
  if (SpecialMsg) {
    forwardMsg = await SpecialMsg.msg()
    special = SpecialMsg.type
  } else {
    // 正常处理
    try {
      forwardMsg = await Bot.makeForwardMsg([
        {
          message: dealMessage(rawMsg.message),
          nickname: e.group.pickMember(e.user_id).card,
          user_id: e.user_id
        }
      ], true)
    } catch (err) {
      logger.error(Log_Prefix, err)
      logger.error(rawMsg)
      forwardMsg = `制作转发消息失败：${err.message}`
    }
  }
  // 判断是否管理撤回
  let isManage = ""
  if (e.operator_id != e.user_id) {
    isManage = `撤回管理：${e.group.pickMember(e.operator_id).card}(${e.operator_id})\n`
  }
  isManage ? logger.info(`${Log_Prefix} 群聊管理撤回`) : logger.info(`${Log_Prefix} 群聊撤回`)
  // 发送的消息
  msg = [
    segment.image(`https://p.qlogo.cn/gh/${e.group_id}/${e.group_id}/100`),
    `[通知(${e.self_id}) - 群聊${isManage ? "管理" : ""}撤回]\n`,
    `撤回群名：${e.group_name}\n`,
    `撤回群号：${e.group_id}\n`,
    isManage,
    `${isManage ? "被撤回人" : "撤回人员"}：${e.group.pickMember(e.user_id).card
    }(${e.user_id})\n`,
    `撤回时间：${moment.unix(e.time).format("MM-DD HH:mm:ss")}`,
    special ? `\n特殊消息：${special}` : ""
  ]
  sendMsg(bot, msg, forwardMsg)
})

Bot.on?.("notice.friend.recall", async (e) => {
  const bot = e.bot ?? Bot

  if (!Config.getNotice(e.self_id).PrivateRecall) return false

  if (e.user_id == bot.uin) return false

  if (Config.masterQQ.includes(e.user_id)) return false

  logger.info(`${Log_Prefix} 好友撤回`)

  let rawMsg = JSON.parse(await redis.get(redisKeyPrePrivate + e.message_id))

  if (!rawMsg) return false
  let forwardMsg = null
  let msg = null
  const SpecialMsg = getSpecialMsgType(rawMsg)
  if (SpecialMsg) {
    forwardMsg = await SpecialMsg.msg()
    rawMsg = SpecialMsg.type
  }
  // 消息
  msg = [
    segment.image(`https://q1.qlogo.cn/g?b=qq&s=100&nk=${e.user_id}`),
    `[消息(${e.self_id}) - 好友撤回消息]\n`,
    `好友账号：${e.user_id}\n`,
    `撤回时间：${moment.unix(e.time).format("MM-DD HH:mm:ss")}\n`,
    "撤回消息：",
    ...dealMessage(rawMsg.message)
  ]
  sendMsg(e.bot ?? Bot, msg, forwardMsg)
})
async function sendMsg(bot, msg, forwardMsg = null) {
  await common.sendMasterMsg(msg, bot.uin)
  if (forwardMsg) {
    try {
      await common.sendMasterMsg(forwardMsg, bot.uin)
    } catch (err) {
      logger.error(Log_Prefix, err)
      await common.sendMasterMsg(`发送失败：${err.message}`, bot.uin)
    }
  }
}
function dealMessage(message) {
  let res2 = []
  for (let i of Array.isArray(message) ? message : [message]) {
    if (i?.type !== "long_msg") res2.push(i)
  }
  return res2
}
function getSpecialMsgType(e) {
  let target = e.group_id ? Bot.pickGroup(e.group_id) : Bot.pickUser(e.user_id)
  let res2 = dealMessage(e.message)

  const { type, url, file } = res2?.[0] || {}
  const member = e.group_id ? target.pickMember(e.user_id) : target
  const nickname = member.info?.card || member.info?.nickname

  const msgType = {
    flash: {
      msg: async () => await target.makeForwardMsg([
        {
          message: segment.image(url),
          nickname,
          user_id: e.user_id
        }
      ]),
      type: "[闪照]"
    },
    record: {
      msg: () => url ? segment.record(url) : "语音不存在",
      type: "[语音]"
    },
    video: {
      msg: () => segment.video(file),
      type: "[视频]"
    },
    xml: {
      msg: () => res2,
      type: "[XML消息]"
    },
    json: {
      msg: () => res2,
      type: "[JSON消息]"
    },
    file: {
      msg: async () => await target.getFileUrl(res2[0].fid, res2[0].md5),
      type: "[文件]"
    }
  }
  return msgType[type]
}